package com.lishe.lishe.lishe.module.auth.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.lishe.lishe.R;
import com.lishe.lishe.asynchttp.LSWebHelper;
import com.lishe.lishe.lishe.module.auth.http.AuthHttpHelper;
import com.lishe.lishe.lishe.module.excitation.activity.CompanyConfirmActivity;
import com.lishe.lishe.lishe.module.excitation.activity.CompanyListActivity;
import com.lishe.lishe.lishe.module.main.http.HttpAppUpdata;
import com.lishe.lishe.lishe.module.mall.event.GoodsDetailRefreshEvent;
import com.lishe.lishe.lishe.utils.EncryptUtil;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.LogUtil;
import com.lishe.lishe.lishe.utils.SharedPreferencesUtils;
import com.lishe.lishe.lishe.utils.ToastUtil;
import com.lishe.lishe.lishe.utils.ValidationUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

/**
 * Created by zhcase on 2017/9/5.
 * <p>
 * 登录
 */

public class LoginFragment extends AuthBaseFragment implements View.OnClickListener {

    public static final String TAG = LoginFragment.class.getSimpleName();


    private ViewPager viewPager = null;

    private EditText inputText1, inputText2;

    Button submitBtn;


    public LoginFragment() {
    }

    public static LoginFragment newInstance(String from) {
        LoginFragment instance = new LoginFragment();
        Bundle bundle = new Bundle();
        bundle.putString("from", from);
        instance.setArguments(bundle);
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View containerFragment = inflater.inflate(R.layout.activity_auth_login, container, false);

        WindowManager wm = (WindowManager) this.getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;         // 屏幕宽度（像素）
        int height = dm.heightPixels;

        int paddingWidth = width * 55 / 752;//内容左右间隔


        ImageButton backTitle = (ImageButton) containerFragment.findViewById(R.id.back_title);
        backTitle.setOnClickListener(this);

        inputText1 = (EditText) containerFragment.findViewById(R.id.inputText1);
        inputText1.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});


        inputText2 = (EditText) containerFragment.findViewById(R.id.inputText2);
        submitBtn = (Button) containerFragment.findViewById(R.id.submitBtn);
        submitBtn.setOnClickListener(this);

        TextView redirectBtn1 = (TextView) containerFragment.findViewById(R.id.redirectBtn1);
        redirectBtn1.setClickable(true);
        redirectBtn1.setOnClickListener(this);

        TextView redirectBtn2 = (TextView) containerFragment.findViewById(R.id.redirectBtn2);
        redirectBtn2.setClickable(true);
        redirectBtn2.setOnClickListener(this);

        TextView redirectBtn3 = (TextView) containerFragment.findViewById(R.id.redirectBtn3);
        redirectBtn3.setClickable(true);
        redirectBtn3.setOnClickListener(this);

        return containerFragment;
    }

    @Override
    public void onClick(View view) {

        if (view.getId() == R.id.back_title) {
            getActivity().finish();
        } else if (view.getId() == R.id.redirectBtn1) {
            if (mJumper != null)
                mJumper.jumpToFragmentForward(FragmentAuthContants.TAB_INDEX_Reg);
        } else if (view.getId() == R.id.redirectBtn2) {

            //忘记密码
            //viewPager.setCurrentItem(FragmentAuthContants.TAB_INDEX_ForgetPwd,true);
            if (mJumper != null)
                mJumper.jumpToFragmentForward(FragmentAuthContants.TAB_INDEX_ForgetPwd);
        } else if (view.getId() == R.id.redirectBtn3) {
            //viewPager.setCurrentItem(FragmentAuthContants.TAB_INDEX_Active,true);
            if (mJumper != null)
                mJumper.jumpToFragmentForward(FragmentAuthContants.TAB_INDEX_Active);
        } else {
            if (view.getId() == R.id.submitBtn) {//登录按钮
                final String userName = inputText1.getText().toString().trim();
                final String password = inputText2.getText().toString().trim();
                if (userName == null || userName.equals("")) {
                    Toast.makeText(getActivity(), "请输入手机号码", Toast.LENGTH_SHORT).show();
                    return;
                }
                //验证手机号码
                if (!ValidationUtils.isMobileNO(userName)) {
                    Toast.makeText(getActivity(), "手机号码格式有误！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (password == null || password.equals("")) {
                    Toast.makeText(getActivity(), "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!ValidationUtils.isLimitPass(password)) {
                    Toast.makeText(getActivity(), R.string.LimitPass, Toast.LENGTH_SHORT).show();
                    return;
                }
                SharedPreferencesUtils.savePhone(userName, getActivity());
                LoadingUtils.createLoadingDialog(getActivity(), "请稍等...", true);
                ToastUtil.showToast(getActivity(), EncryptUtil.md5(password) + "");
                AuthHttpHelper.doLogin(getActivity(), userName, EncryptUtil.md5(password), new LSWebHelper.WebCallBack() {
                    @Override
                    public void onSuccess(JSONObject dataJson, String dataString, String message) {
                        LoadingUtils.closeDialog();
                        int comSize = dataJson.optInt("comSize");
                        LogUtil.i("comSize", comSize + ".......");
                        SharedPreferencesUtils.saveComSize(comSize, getActivity());
                        if (comSize > 1) {//非散户跳到企业选择企业
                            CompanyListActivity.jump(getActivity(), 0);
                        } else if (comSize == 1) {//跳到企业确认页
                            CompanyConfirmActivity.jump(getActivity(),"-1",true);
                        }

                        //注册极光推送RegistrationID
                        if(!TextUtils.isEmpty(SharedPreferencesUtils.getRegistrationID())){
                            HttpAppUpdata.updateDevice(SharedPreferencesUtils.getRegistrationID());
                        }
                        getActivity().finish();
                        EventBus.getDefault().post(new GoodsDetailRefreshEvent());
                    }

                    @Override
                    public void onFailure(String message) {
                        LoadingUtils.closeDialog();
                        if (isAdded()) {
                            Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        }
    }


//    private boolean isAlllInputsValid()
//    {
//        final String userName = inputText1.getText().toString().trim();
//        final String password = inputText2.getText().toString().trim();
//
//        if (userName == null || userName.equals("")) {
//            return false;
//        }
//
//        //验证手机号码
//        if (!ValidationUtils.isMobileNO(userName)) {
//            return false;
//        }
//
//        if (password == null || password.equals("") || password.length()<6 || password.length()>20) {
//            return false;
//        }
//
//        return true;
//    }
//
//    private TextWatcher loginInputWatcher = new TextWatcher() {
//
//        @Override
//        public void onTextChanged(CharSequence s, int start, int before, int count) {
//            // TODO Auto-generated method stub
//
//        }
//
//        @Override
//        public void beforeTextChanged(CharSequence s, int start, int count,
//                                      int after) {
//            // TODO Auto-generated method stub
//
//        }
//
//        @Override
//        public void afterTextChanged(Editable s) {
//
//            if(isAlllInputsValid())
//            {
//                submitBtn.setEnabled(true);
//            }else
//            {
//                submitBtn.setEnabled(false);
//            }
//        }
//    };

}